﻿using System;
using System.Collections.Generic;
using System.Text;

namespace LeetcodeTest._100._10
{
    public class Leetcode7
    {
        public void Test()
        {
            try
            {
                reverse(-1563847412);
                reverse(901000);
        
            }
            catch (Exception ex)
            { }
        }


        /*
         7. Reverse Integer

         Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321
             */

            /// <summary>
            /// 更快
            /// </summary>
            /// <param name="x"></param>
            /// <returns></returns>
        int reverse(int x)
        {
            bool isMinus = false;
            
            if (x< 0)
            {
                long lX = Convert.ToInt64(x);
                isMinus = true;
                lX = Math.Abs(lX);
                if (lX > int.MaxValue)
                    return 0;
                x = Math.Abs(x);
            }


            int iDivisor = 1000000000;
            int iMultiplier = 1;
            long longNum = 0;
            long tempResut = 0;
            bool isFirstLoop = true;
            while (iDivisor > 0)
            {
                tempResut = x / iDivisor;
                if (tempResut == 0)
                {
                    if (!isFirstLoop)
                    {
                        iMultiplier = iMultiplier * 10;
                    }
                    iDivisor = iDivisor / 10;

                    continue;
                }
                isFirstLoop = false;
                x = x % iDivisor;
                iDivisor = iDivisor / 10;
                longNum += tempResut * iMultiplier;
                iMultiplier = iMultiplier * 10;
            }

            if (!isMinus)
            {
                if (longNum > int.MaxValue)
                    return 0;
            }
            else
            {
                longNum = -longNum;
                if (longNum < int.MinValue)
                    return 0;
            }
            return Convert.ToInt32(longNum);
        }
        int reverse2(int x)
        {
            string strX = x.ToString();
            string tempX = "";
            bool isMinus = false;
            if (x < 0)
            {
                isMinus = true;
                strX = strX.Substring(1);
            }
            for (int i = strX.Length - 1; i >= 0; i--)
            {
                tempX += strX[i];
            }
            if (isMinus)
                tempX = "-" + tempX;

            long l = Convert.ToInt64(tempX);
            if (!isMinus)
            {
                if (l > int.MaxValue)
                    return 0;
            }
            else
            {
                if (l < int.MinValue)
                    return 0;
            }
            return Convert.ToInt32(l);
        }
    }
}
